﻿using System;
using System.Collections.Generic;
using System.Configuration.Provider;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using ZJ.Finance.DataModel;

namespace ZJ.Finance.BusinessRule
{
    public abstract partial class DataProvider : ProviderBase
    {
        public static string GetJosnp(string content)
        {
            return String.Format("{0}({1});", HttpContext.Current.Request.QueryString["callback"], content);
        }

        public static string RetrunData(object errorId, object errorObj)
        {
            var datas = new Dictionary<string, object> { { "Error", errorId }, { "Data", errorObj } };
            return JsonConvert.SerializeObject(datas, new JavaScriptDateTimeConverter());
        }

        public static string GetMd5(string content)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(content, "MD5");

        }

        public static User GetCurrentUser()
        {
            try
            {
                string cookieName = FormsAuthentication.FormsCookieName;

                HttpCookie authCookie = HttpContext.Current.Request.Cookies[cookieName];
                if (authCookie == null)
                {
                    //FormsAuthentication.RedirectToLoginPage();
                    HttpContext.Current.Response.Redirect(ResolveClientUrl("~/Error.html"));
                    return null;
                }
                FormsAuthenticationTicket tickey = FormsAuthentication.Decrypt(authCookie.Value);
                if (tickey != null)
                {
                    var userStr = tickey.Name;
                    var user = JsonConvert.DeserializeObject<User>(userStr);
                    return user;
                }
                HttpContext.Current.Response.Redirect(ResolveClientUrl("~/Error.html"));
                return null;
            }
            catch (Exception ex)
            {
                //FormsAuthentication.RedirectToLoginPage();
                HttpContext.Current.Response.Redirect(ResolveClientUrl("~/Error.html"));
                return null;
            }
        }

        public static string ResolveClientUrl(string url)
        {
            return HttpContext.Current.Server.MapPath(url);
        }
    }
}
